package com.va.wsserver;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint( "/endpoint" )
public class MyWSEndpoint
{
    private static Set<Session> peers = Collections.synchronizedSet( new HashSet<Session>() );
    private static final Logger log = Logger.getLogger( MyWSEndpoint.class.getName() );

    @OnOpen
    public void handleOpen( Session peer, EndpointConfig config )
    {
        log.info( "Adding peer " + peer.getId() );
        peers.add( peer );
        log.info( "Pear " + peer.getId() + " added" );
    }

    @OnClose
    public void handleClose( Session peer, CloseReason reason )
    {
        log.info( "Peer " + peer.getId() + "closed because " + reason.toString() );
        peers.remove( peer );
    }

    @OnMessage
    public void handleMessage( Session peer, String message )
    {
        log.info( "Received from : \"" + peer.getId() + "\" message: " + message );
        String reply = "Echo: " + message;
        log.info( "Sending to peer: \"" + reply + "\"" );
        sendMessage( peer, reply );
    }

    @OnError
    public void handleError( Session peer, Throwable t )
    {
        log.info( peer.getId() + "is on error: " + t.getMessage() );
    }

    private void sendBroadCast( String message )
    {
        try
        {
            for ( Iterator<Session> it = peers.iterator(); it.hasNext(); )
            {
                Session session = it.next();
                if ( session.isOpen() )
                {
                    session.getBasicRemote().sendText( message );
                }
            }
        }
        catch ( IOException ex )
        {
            Logger.getLogger( MyWSEndpoint.class.getName() ).log( Level.SEVERE, null, ex );
        }
    }

    private void sendMessage( Session session, String message )
    {
        try
        {
            session.getBasicRemote().sendText( message );
        }
        catch ( IOException ex )
        {
            log.info( "Exception while send echo: " + ex.getMessage() );
        }
    }

}
